package emby.stmt;

import java.util.List;

import emby.EmbyRuntime;
import emby.err.TypeError;
import emby.expr.Expression;
import emby.expr.Variable;
import emby.lang.Block;
import emby.lang.Scope;
import emby.writer.IEmbyCodifier;

public class EnhancedFor extends Statement{

	private static final long serialVersionUID = 1523705250018092652L;
	Variable var;
	Expression iterable;
	Block body;
	public EnhancedFor(Variable var, Expression iterable, Block _body){
		this.var = var;
		this.iterable = iterable;
		body = _body;
	}

	/**
	 * Always returns null UNLESS there was a return statement in the block.
	 */
	@Override
	public Object eval(Scope s) {
		//Scope subscope = new Scope(s);
		if(EmbyRuntime.echo){
			emby.util.Print.println("Evaluating enhanced for loop. Variable: "+var+" iterator: "+iterable);
		}
		Object iterate = iterable.eval(s);
		if( iterate instanceof List<?>){
			return evalList(s, (List<?>)iterate);
		}
		if(!(iterate instanceof Iterable)){
			throw new TypeError(iterable.getLine(),iterate+" is not compatible with enhanced for because it is not iterable.");
		}
		Iterable<?> iter = (Iterable<?>) iterate;
		for( Object o: iter){
			s.setVar(var.getName(), o);
			Object retValue = body.eval(s);
			if(retValue!=null){
				return retValue;
			}
		}
		return null;
	}
	
	public Object evalList(Scope s, List<?> iter){
		for( Object o : iter){
			s.setVar(var.getName(), o);		
			Object retValue = body.eval(s);
			o = s.getVar(lineNum, var.getName());
			if(retValue!=null){
				return retValue;
			}
		}
		return null;
	}
	
	public void codify(IEmbyCodifier ec){
		ec.fore(var, iterable, body);
	}
}